<template>
  <a-spin :spinning="loading" tip="校验关键词中...">
    <scrollbar class="scrollbar">
      <a-form-item>
        <template #label> 已选词({{ formFields.result.length }}/{{ data.combinedWordNum }}) </template>
        <a-tag
          color="red"
          class="mb-2 text-sm font-normal leading-6"
          closable
          @close.prevent="handleRemove(item)"
          :key="item"
          v-for="item in formFields.result"
          >{{ item }}</a-tag
        >
      </a-form-item>
      <a-form-item
        label="(A组)地区"
        name="areas"
        class="area-disable"
        :rules="{
          required: true,
          trigger: 'change',
          message: '请选择推广区域'
        }"
        @click="showAreas = true"
      >
        <a-select
          placeholder="请选择推广区域"
          mode="multiple"
          :value="formFields.areas"
          :options="serviceAreasOptions"
          disabled
        />
      </a-form-item>
      <a-form-item
        label="(B组)关键词"
        name="keyword"
        :rules="{
          required: true,
          trigger: 'change',
          validator: checkKeywordCount
        }"
      >
        <a-textarea
          v-model:value="formFields.word"
          :auto-size="{ minRows: 4, maxRows: 4 }"
          :placeholder="keywordPlaceholder"
          @change="handleKeyword"
        />
      </a-form-item>
      <a-form-item
        label="(C组)后缀"
        name="suffix"
        :rules="{
          required: true,
          trigger: 'change',
          validator: checkSuffixCount
        }"
      >
        <a-select
          :value="formFields.suffix"
          mode="multiple"
          placeholder="请选择活动状态"
          :options="suffixOptions"
          @change="handleSuffixChange"
        />
      </a-form-item>
      <div v-show="abcKind.length">
        <h3 class="mb-0">组词列表</h3>
        <divider m="15px 0 0 0"></divider>
        <a-tabs v-show="abcKind.length" tab-position="left" class="tabs">
          <a-tab-pane key="1" tab="AB组合词" force-render>
            <a-checkbox-group class="word-checkbox" v-model:value="ab" :options="abKind" />
          </a-tab-pane>
          <a-tab-pane key="2" tab="BC组合词" force-render>
            <a-checkbox-group class="word-checkbox" v-model:value="bc" :options="bcKind" />
          </a-tab-pane>
          <a-tab-pane key="3" tab="ABC组合词" force-render>
            <a-checkbox-group class="word-checkbox" v-model:value="abc" :options="abcKind" />
          </a-tab-pane>
        </a-tabs>
      </div>
    </scrollbar>
  </a-spin>
  <BwArea
    :loadis="true"
    v-model:show="showAreas"
    :max="5"
    @change="handleAreaChange"
    ref="BwAreaRef"
    @limit="handleAreaLimit"
  >
    <template #title> 区域选择（最多只能选5个区域） </template>
  </BwArea>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, defineProps } from 'vue'
import { message } from 'ant-design-vue'
import { useVModel } from '@vueuse/core'
import { keywordPlaceholder } from '@/shared/text'
import { Rule } from 'ant-design-vue/lib/form'
import BwArea from '@/views/price-sheet/components/BwArea.vue'
import { emojiMatcher } from '@/utils'
import type { ComposableState } from '@/views/promotion/interface'
import Scrollbar from '@/components/scrollbar/index.vue'
import Divider from '@/components/divider/index.vue'
import validateFreeWord from '@/services/order/validateFreeWord'
import type { Promotion } from '@/core/interfaces/promotion'
import { uniq } from 'lodash-es'
import getFreeWordSuffix from '@/services/promotion/getFreeWordSuffix'

interface Props {
  data: ComposableState
  record: Partial<Promotion>
  visible: boolean
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  message: String
})

const max = 5
const BwAreaRef = ref<InstanceType<typeof BwArea>>()
const showAreas = ref(false)
const formFields = useVModel(props, 'data')
const loading = ref(false)
const [, validFreeWord] = validateFreeWord()
const [suffixOptions, fetchSuffix] = getFreeWordSuffix()

const ab = computed({
  get() {
    return formFields.value.result.filter((item) => abKind.value.includes(item))
  },
  set(selected: string[]) {
    selectedSetterProxy(abKind.value, selected)
  }
})
const bc = computed({
  get() {
    return formFields.value.result.filter((item) => bcKind.value.includes(item))
  },
  set(selected: string[]) {
    selectedSetterProxy(bcKind.value, selected)
  }
})
const abc = computed({
  get() {
    return formFields.value.result.filter((item) => abcKind.value.includes(item))
  },
  set(selected: string[]) {
    selectedSetterProxy(abcKind.value, selected)
  }
})

const serviceAreasOptions = computed(() => {
  return formFields.value.areas.reduce<{ label: string; value: string }[]>((prev, next) => {
    prev.push({
      label: next,
      value: next
    })
    return prev
  }, [])
})

function pushWord(kinds: string[], selected: string[]) {
  kinds
    .filter((text) => !selected.includes(text))
    .forEach((text) => {
      const i = formFields.value.result.findIndex((d) => d === text)
      if (i > -1) {
        formFields.value.result.splice(i, 1)
      }
    })
  selected.forEach((text) => {
    if (!formFields.value.result.find((d) => d === text)) {
      formFields.value.result.push(text)
    }
  })
}

async function selectedSetterProxy(kinds: string[], selected: string[]) {
  console.log(formFields.value.result)
  if (props.data.combinedWordNum > formFields.value.result.length) {
    const curVal = selected.find((item) => !formFields.value.result.includes(item))

    if (curVal) {
      loading.value = true
      const [err, res] = await validFreeWord({
        name: curVal,
        orderId: props.record.orderId,
        clientType: props.record.clientType!
      })

      if (!err) {
        pushWord(kinds, selected)

        message.success(res.data.data)
      } else {
        message.error(err?.message)
      }
      loading.value = false
    } else {
      pushWord(kinds, selected)
    }
  } else {
    message.error('选词已超过上限')
  }
}

// bc类 地区a+关键词b
const abKind = computed(() => {
  return formFields.value.keyword.reduce<string[]>((kinds, b) => {
    return kinds.concat(
      formFields.value.areas.map((a) => {
        return `${a}${b}`
      })
    )
  }, [])
})

// bc类 关键词b+后缀词c
const bcKind = computed(() => {
  return formFields.value.keyword.reduce<string[]>((kinds, b) => {
    return kinds.concat(
      formFields.value.suffix.map((c) => {
        return `${b}${c}`
      })
    )
  }, [])
})

// abc类
const abcKind = computed(() => {
  return formFields.value.suffix.reduce<string[]>((kinds, c) => {
    return kinds.concat(
      abKind.value.map((text) => {
        return `${text}${c}`
      })
    )
  }, [])
})

function handleRemove(item: string) {
  const i = formFields.value.result.findIndex((d) => d === item)
  formFields.value.result.splice(i, 1)
}

function checkSuffixCount(_rule: Rule, value: string[]) {
  if (!value || value.length === 0) {
    return Promise.reject('请选择后缀')
  } else if (value.length > max) {
    return Promise.reject(`后缀选择不能超过${max}个`)
  } else {
    return Promise.resolve()
  }
}

function checkKeywordCount() {
  const count = handleParticiple()
  if (count.length > 5) {
    return Promise.reject(`关键词不能超过${max}个`)
  } else if (count.length === 0) {
    return Promise.reject('请输入关键词')
  } else if (emojiMatcher(formFields.value.word)) {
    return Promise.reject('推广关键词中存在如：表情等非法字符')
  }
  return Promise.resolve()
}

function handleAreaChange(cityMap: Record<string, string[]>) {
  formFields.value.areas = Object.keys(cityMap).reduce<string[]>((data, key) => {
    return data.concat(cityMap[key])
  }, [])
}

function handleSuffixChange(suffix: string[]) {
  if (suffix.length > max) {
    message.error(`后缀选择不能超过${max}个`)
  } else {
    formFields.value.suffix = suffix
  }
}

function handleAreaLimit() {
  message.error('地区选择不能超过五个')
}

function handleParticiple() {
  return formFields.value.word
    .toLowerCase()
    .split(/[\n\r\s,，;；]+/g)
    .filter((t) => t !== '')
}

function handleKeyword() {
  formFields.value.keyword = uniq(handleParticiple())
}

onMounted(() => {
  fetchSuffix()
})

defineExpose({
  bwAreaReset: () => BwAreaRef.value.handleReset()
})
</script>

<style lang="scss" scoped>
.area-disable {
  ::v-deep(.ant-select-disabled.ant-select:not(.ant-select-customize-input) .ant-select-selector) {
    background: transparent;
    color: inherit;
    cursor: pointer;
  }

  ::v-deep(.ant-select-disabled.ant-select-multiple .ant-select-selection-item) {
    color: inherit;
    cursor: pointer;
  }
}

.scrollbar {
  max-height: 75vh;
}

.word-checkbox {
  ::v-deep(.ant-checkbox) {
    display: none;
  }

  ::v-deep(.ant-checkbox + span) {
    padding: 2px 10px;
  }

  &::v-deep(.ant-checkbox + span) {
    border: 1px solid #ff9395;
    border-radius: 5px;
    padding: 2px 10px;
    user-select: none;
  }

  &::v-deep(.ant-checkbox.ant-checkbox-checked + span) {
    background: #ff4d4f;
    color: #fff;
    border: 1px solid #ff4d4f;
    border-radius: 5px;
    padding: 2px 10px;
  }

  &::v-deep(.ant-checkbox-wrapper) {
    margin-top: 8px;
  }
}

.tabs {
  &::v-deep(.ant-tabs-nav) {
    width: 90px;
    padding-top: 15px;

    .ant-tabs-tab {
      padding: 0;

      .ant-tabs-tab-btn {
        font-size: 14px;
      }
    }
  }

  &::v-deep(.ant-tabs-content) {
    padding-top: 6px;
  }
}
</style>
